package com.abc20230319.demo;

import lombok.extern.slf4j.Slf4j;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.stream.Collectors;

@Slf4j
public class PostFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) {
        System.out.println("postFilter init...");
        log.info("PostFilter.init");
    }

    /*
     *  请求被拦截的时候调用
     * */
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        System.out.println("postFilter do...");
        log.info("PostFilter.doFilter");
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;
        String jsonSt;
        if ("POST".equalsIgnoreCase(req.getMethod())) {
            req = new RequestWrapper(req);
            jsonSt = req.getReader().lines().collect(Collectors.joining(System.lineSeparator()));
            System.out.println(jsonSt);
            chain.doFilter(req, res); //未解决流的问题前，Controller层的@RequestBody会报错！
            return;
        }
        res.sendError(333, "您没有权限！");
    }


    /*
     * 容器被销毁的时候调用
     * */
    @Override
    public void destroy() {
        System.out.println("postFilter destroy...");
        log.info("PostFilter.destroy");
    }
}

/*解决Controller层@RequestBody报错的问题：https://www.cnblogs.com/yyfyy/p/17151175.html*/
@Slf4j
class RequestWrapper extends HttpServletRequestWrapper {

    private String body;

    public RequestWrapper(HttpServletRequest request) {
        super(request);
        try (BufferedReader reader = request.getReader()) {
            body = reader.lines().collect(Collectors.joining());
        } catch (Exception e) {
            log.error("!!-- read request from requestbody error", e);
        }
    }

    @Override
    public BufferedReader getReader() {
        return new BufferedReader(new InputStreamReader(this.getInputStream()));
    }

    @Override
    public ServletInputStream getInputStream() {
        final ByteArrayInputStream byteArrayIns = new ByteArrayInputStream(body.getBytes());
        ServletInputStream servletIns = new ServletInputStream() {
            @Override
            public boolean isFinished() {
                return false;
            }

            @Override
            public boolean isReady() {
                return false;
            }

            @Override
            public void setReadListener(ReadListener readListener) {

            }

            @Override
            public int read() {
                return byteArrayIns.read();
            }
        };
        return servletIns;
    }

    public String getBody() {
        return body;
    }

    public void setBody(String body) {
        this.body = body;
    }
}
